package com.xinke.edu.mypetadoption.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.xinke.edu.mypetadoption.Main2Activity;
import com.xinke.edu.mypetadoption.Main3Activity;
import com.xinke.edu.mypetadoption.MainActivity;
import com.xinke.edu.mypetadoption.MerchantActivity;
import com.xinke.edu.mypetadoption.databinding.LoginAcritvtyBinding;
import com.xinke.edu.mypetadoption.entity.ResultBody;
import com.xinke.edu.mypetadoption.entity.User;
import com.xinke.edu.mypetadoption.net.RetrofitUtil;
import com.xinke.edu.mypetadoption.util.SPUtils;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class Login_Activity extends AppCompatActivity {
    LoginAcritvtyBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = LoginAcritvtyBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());

        //恢复勾选“记住我”
        boolean wasRemembered = !TextUtils.isEmpty(SPUtils.getInstance(this).getString("account",""));
        binding.cbRemember.setChecked(wasRemembered);

        // 恢复保存的账号密码
        binding.loginUsername.setText(SPUtils.getInstance(this).getString("account", ""));
        binding.loginPassword.setText(SPUtils.getInstance(this).getString("password", ""));

        // 注册按钮点击事件
        binding.register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Login_Activity.this, CreateAccountActivity.class);
                startActivity(intent);
            }
        });


        // 登录按钮点击事件
        binding.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });

    }

    public void login() {
        String username = binding.loginUsername.getText().toString();
        String password = binding.loginPassword.getText().toString();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "账号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.length() < 6 || password.length() > 16) {
            Toast.makeText(this, "请设置6-16位密码", Toast.LENGTH_SHORT).show();
            return;
        }

        //判断勾选“记住我”
        boolean isRememberChecked = binding.cbRemember.isChecked();

        RetrofitUtil.getApi().login(username,password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBody<User>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResultBody<User> userResultBody) {
                        if (userResultBody.getData() != null) {
                            User user = userResultBody.getData();
                            Toast.makeText(Login_Activity.this, "登录成功！欢迎 " + user.getUsername(), Toast.LENGTH_SHORT).show();

                            // 保存用户ID - 使用正确的int类型存储
                            SPUtils.getInstance(Login_Activity.this).putInt("userId", user.getId());

                            // 处理"记住我"功能
                            if (binding.cbRemember.isChecked()) {
                                SPUtils.getInstance(Login_Activity.this).putString("account", user.getUsername());
                                SPUtils.getInstance(Login_Activity.this).putString("password", user.getPassword());
                            } else {
                                SPUtils.getInstance(Login_Activity.this).putString("account", "");
                                SPUtils.getInstance(Login_Activity.this).putString("password", "");
                            }
                            
                            // 根据用户角色跳转不同页面
                            if (user.getRole() == 1) { // 管理员
                                // 跳转管理员主界面
                                Intent intent = new Intent(Login_Activity.this, Main3Activity.class);
                                startActivity(intent);
                            } else if (user.getRole() == 2) { // 商家
                                // 跳转商家主页面
                                if (user.getStatus() == 0){
                                    //商家资质未审核通过
                                    Intent intent = new Intent(Login_Activity.this, MerchantActivity.class);
                                    startActivity(intent);
                                }
                                Intent intent = new Intent(Login_Activity.this, Main2Activity.class);
                                startActivity(intent);
                            } else if (user.getRole() == 3) { // 普通用户
                                // 跳转用户主页面
                                Intent intent = new Intent(Login_Activity.this, MainActivity.class);
                                startActivity(intent);

                            }
                            finish(); // 关闭登录界面
                        } else {
                            Toast.makeText(Login_Activity.this, "!!!登录失败：" + userResultBody.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Toast.makeText(Login_Activity.this, "网络错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放Binding资源（避免内存泄漏）
        binding = null;
    }
}